<?php

namespace Beerus\Modules\Brand\Controllers;

use App\Admin\Extensions\WorkContent;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Beerus\Modules\Brand\Extensions\Tools\BatchClaimWikiAudit;
use Beerus\Modules\Brand\Extensions\Tools\BatchClaimWikiEditAudit;
use Biz\model\brand\Brand as mBrand;
use Biz\model\store\StoreBasic;
use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\WikiBasic as mWikiBasic;
use Biz\model\wiki\WikiBasicLog as mWikiBasicLog;
use Biz\service\wiki\AdmWikiBasic;
use Biz\service\wiki\AdmWikiBasic as sAdmWikiBasic;
use Biz\service\wiki\WikiBasic;
use Doraemon\model\NewTag\Tag;
use Doraemon\service\Category;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Tools\BatchActions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use UnexpectedValueException;

class WikiController extends Controller
{
    const PAGE_SIZE = 20;
    const SOURCE_CATEGORY_LIST = '/admin/extend/category/child';
    const STATE_MAP = [
        0 => '待审核',
        1 => '审核通过',
        2 => '审核不通过',
    ];

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        Admin::style('.span-label{margin-bottom: 5px; cursor: pointer; margin-right: 5px; display: inline-block;}');
        Admin::script($this->auditScript());
        Admin::script($this->changeScript());
        Admin::script($this->reloadScript());
        Admin::script($this->deleteChebox());

        if (!$request->input('basic_state')) {
            $request->merge([
                'basic_state' => 0,
            ]);
        }
        if (!$request->input('wiki_basic_type')) {
            $request->merge([
                'wiki_basic_type' => mWikiBasic::WIKI_BASIC_BRAND,
            ]);
        }
        $request_data = $request->all();
        $condition = self::getCondition($request_data);
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        if (!is_null($condition)) {
            $where = $condition;
            $where['LIMIT'] = [
                ($page - 1) * $page_size,
                $page_size,
            ];
            $result = sAdmWikiBasic::admGetAuditWikiList($where);
        } else {
            $result = ['list' => [], 'total' => 0];
        }
        $list = [];
        if ($result['total'] > 0) {
            foreach ($result['list'] as $row) {
                $spuList = $row['spu_list'];
                $row['expand'] = $this->_getWikiExpand($spuList, $request_data['wiki_basic_type']);
                $list[] = $row;
            }
        }
        $gridModel = new pGridDataModel($list, $result['total'], [
            'perPage' => $page_size,
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $request_data) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->tools(function (Grid\Tools $tools) use ($request_data) {
                    $tools->batch(function (BatchActions $batch) use ($request_data) {
                        $batch->disableDelete();
                        if ($request_data['basic_state'] == mWikiBasic::STATE_NORMAL) {
                            $batch->add('批量审核通过', new BatchClaimWikiAudit(1));
                        }
                    });
                });


                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('wiki_basic_type', '门店/品牌')->select(mWikiBasic::WIKI_BASIC_TYPE);
                        $filter->equal('basic_state', 'wiki状态')->select(self::STATE_MAP);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->dropDown('wiki_value', [
                            'wiki_id' => 'wiki ID',
                            'wiki_title' => 'wiki名称',
                        ]);
                        $filter->dropDown('brand_value', [
                            'brand_id' => '品牌ID',
                            'brand_uid' => '品牌uid',
                            'brand_name' => '品牌名称',
                        ]);
                        $filter->dropDown('store_value', [
                            'store_id' => '门店ID',
                            'store_uid' => '门店uid',
                            'store_name' => '门店名称',
                        ]);
                    });
                    $filter->expand();
                });
                $grid->column("id", 'wiki ID')->expand(function () {
                    return $this->expand;
                }, true)->width(80);
                $grid->column('title', 'wiki 名称')->width(150)->editable();
                $grid->column('cover_img', '图片')->display(function () {
                    $imgPath = $this->cover_img;
                    $id = $this->id;
                    $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:200px' class='img img-thumbnail' />" : "";

                    return "<a href='/admin/brand/wiki/img/edit?id={$id}'>" . $image . "</a>";
                })->width(100);
                $grid->column('series', '系列')->display(function () {
                    $html = '';
                    $arr = explode(',', $this->series);
                    foreach ($arr as $row) {
                        $html .= '<div class="span-label"><span class="label label-success">' . $row . '</span></div>';
                    }

                    return $html;
                })->width(150);
                $grid->column('style', '标签')->display(function () {
                    $html = '';
                    if ($this->style) {
                        $html = '<div>风格</div>';
                        $styleArr = explode(',', $this->style);
                        foreach ($styleArr as $row) {
                            $html .= '<div class="span-label"><span class="label label-success">' . $row . '</span></div>';
                        }
                    }
                    if ($this->material) {
                        $html .= '<div>材质</div>';
                        $materialArr = explode(',', $this->material);
                        foreach ($materialArr as $row) {
                            $html .= '<div class="span-label"><span class="label label-success">' . $row . '</span></div>';
                        }
                    }
                    if ($this->space) {
                        $html .= '<div>所属空间</div>';
                        $spaceArr = explode(',', $this->space);
                        foreach ($spaceArr as $row) {
                            $html .= '<div class="span-label"><span class="label label-success">' . $row . '</span></div>';
                        }
                    }
                    $html .= '</br><a href="javascript:;" class="btn btn-default changeTag" data-type=""  data-id="' . $this->id . '" >更改标签</a>';

                    return $html;
                })->width(200);


                $grid->column("category_name", '分类')->display(function () {
                    $categoryName = '';
                    if ($this->category_name) {
                        $categoryName .= '<div class="span-label"><span class="label label-success">' . $this->category_name . '</span></div>';
                    }
                    if ($this->second_category_name) {
                        $categoryName .= '<div class="span-label"><span class="label label-success">' . $this->second_category_name . '</span></div>';
                    }
                    if ($this->third_category_name) {
                        $categoryName .= '<div class="span-label"><span class="label label-success">' . $this->third_category_name . '</span></div>';
                    }
                    if ($this->four_category_name) {
                        $categoryName .= '<div class="span-label"><span class="label label-success">' . $this->four_category_name . '</span></div>';
                    }
                    if (empty($categoryName)) {
                        $categoryName .= '<span class="delcheckbox"></span>';
                    }

                    return $categoryName . '</br><a href="javascript:;" class="btn btn-default changeCategory" data-type=""   data-id="' . $this->id . '" >更改分类</a>';

                })->width(100);
                if ($request_data['wiki_basic_type'] == mWikiBasic::WIKI_BASIC_BRAND) {
                    $grid->column("brand_id", '品牌')->display(function () {
                        $html = '<ul class="list-unstyled">';
                        $html .= "<li><span class='label label-info'>" . '品牌id' . ':' . $this->brand_id . "</span></li>";
                        $html .= "<li><span class='label label-success'>" . '品牌名称' . ':' . $this->brand_name . "</span></li>";
                        $html .= "<li><span class='label label-warning'>" . '品牌类型' . ':' . mBrand::BRAND_TYPE[$this->brand_type] . "</span></li>";
                        $html .= '</ul>';

                        return $html;
                    })->width(150);
                    $grid->column("brand_logo", '品牌logo')->display(function () {
                        $imgPath = $this->brand_logo;
                        $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:200px' class='img img-thumbnail' />" : "";

                        return $image;
                    })->width(80);
                }
                if ($request_data['wiki_basic_type'] == mWikiBasic::WIKI_BASIC_STORE) {
                    $grid->column("store_id", '门店')->display(function () {
                        $html = '<ul class="list-unstyled">';
                        $html .= "<li><span class='label label-info'>" . '门店id' . ':' . $this->store_id . "</span></li>";
                        $html .= "<li><span class='label label-success'>" . '门店名称' . ':' . $this->store_name . "</span></li>";
                        $html .= '</ul>';

                        return $html;
                    })->width(150);
                    $grid->column("store_logo", '门店logo')->display(function () {
                        $imgPath = $this->store_logo;
                        $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:200px' class='img img-thumbnail' />" : "";

                        return $image;
                    })->width(80);
                }

                $grid->column("basic_state_desc", '状态')->display(function () {
                    if ($this->basic_state != mWikiBasic::STATE_NOT_PASS) {
                        return $this->basic_state_desc;
                    } else {
                        return $this->basic_state_desc . '</br><a href="javascript:;" class="btn btn-default not-pass-reason"  data-id="' . $this->id . '" >原因</a>';
                    }
                })->width(80);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    if (in_array($actions->row->basic_state, [mWikiBasic::STATE_NOT_PASS, mWikiBasic::STATE_NORMAL])) {
                        $actions->prepend('&nbsp;<a class="fa pass-data" data-state="' . mWikiBasic::STATE_PASS . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">审核通过</a>');
                    }
                    if (in_array($actions->row->basic_state, [mWikiBasic::STATE_NORMAL, mWikiBasic::STATE_ONLINE])) {
                        $actions->prepend('&nbsp;<a class="fa not-pass-data" data-state="' . mWikiBasic::STATE_NOT_PASS . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">审核不通过</a>');
                    }
                    if ($actions->row->basic_state == mWikiBasic::STATE_EDIT_AUDIT) {
                        $actions->prepend('&nbsp;<a class="fa" href="' . url('/admin/brand/wiki/editAuditList?wiki_id=' . $actions->row->id) . '">去审核</a>');
                    }
                });
            }
        );

        $tab = new Tab();
        $tab->add('品牌/门店wiki审核', $gridList->render(), true);
        $tab->addLink('品牌/门店wiki编辑待审核', url('/admin/brand/wiki/editAuditList'), false);
        $tab->addLink('品牌/门店wiki图片审核', url('/admin/brand/wiki/imagelist'), false);
        $content->row($tab);

        return $content
            ->header('品牌/门店wiki审核')
            ->description(' ')
            ->breadcrumb(['text' => '品牌/门店wiki审核']);
    }

    private function auditScript()
    {
        return <<<SCRIPT
        $('.pass-data').unbind('click').click(function(){
            var id= $(this).data('id');
            var state=$(this).data('state');
            let url = '/admin/brand/wiki/audit'
            let params = {id:id,state:state}
            $.post(url, params , function (result) {
                if (result.code == 1) {
                    layer.msg(result.title);
                    setTimeout(function () {
                        parent.window.location.reload();
                    }, 2000);
                } else {
                    layer.msg(result.title);
                }
            });
        });
        $('.not-pass-data').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.open({
                type: 2,
                title: '审核不通过',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['700px', '600px'],
                content: '/admin/brand/wiki/audit/'+id+'/unPass',
//                end: function(){
//                    parent.window.location.reload();
//                }
            });
        });
         $('.not-pass-reason').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.open({
                type: 2,
                title: '审核不通过原因',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['700px', '600px'],
                content: '/admin/brand/wiki/unPassLog/'+id,
            });
        });
SCRIPT;
    }

    private function changeScript()
    {
        return <<<SCRIPT
        $('.changeCategory').unbind('click').click(function() {
            var id = $(this).data('id');
            var dataType=$(this).data('type');
            layer.open({
                type: 2,
                title: '更改分类',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['700px', '600px'],
                content: '/admin/brand/wiki/changeCategory/'+id+'?type='+dataType,
//                end: function(){
//                    parent.window.location.reload();
//                }
            });
		});
        $('.changeTag').unbind('click').click(function() {
            var id = $(this).data('id');
            var dataType=$(this).data('type');
            layer.open({
                type: 2,
                title: '更改标签',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['700px', '600px'],
                content: '/admin/brand/wiki/changeTag/'+id+'?type='+dataType,
            });
		});
SCRIPT;
    }

    private function reloadScript()
    {

        return <<<SCRIPT
        $('.reload-data').unbind('click').click(function(){
            let url = '/admin/wiki/admList/' +  $(this).data('id')  + '/reload'
            let params = {}
            $.ajaxSettings.async = true;
            $.post(url, params , function (e) {
                 toastr.success('重新抓取任务已经添加,稍后刷新页面进行查看');
            });
        });
SCRIPT;
    }

    private function deleteChebox()
    {
        return <<<SCRIPT
                $(function(){
                    $(".delcheckbox").parent().siblings(".column-__row_selector__").children("div").remove();
                });
        SCRIPT;
    }

    private static function getCondition($request)
    {
        $condition['ORDER'] = ['wiki_basic.id' => 'DESC'];
        if (isset($request['wiki_id']) && !empty($request['wiki_id'])) {
            $condition['wiki_basic.id'] = $request['wiki_id'];

            return $condition;
        }
        if (isset($request['wiki_title']) && strlen(trim($request['wiki_title'])) > 0) {
            $condition['wiki_basic.title[~]'] = trim($request['wiki_title']);
        }
        if (isset($request['wiki_basic_type']) && !empty($request['wiki_basic_type'])) {
            if ($request['wiki_basic_type'] == mWikiBasic::WIKI_BASIC_BRAND) {
                $condition['wiki_basic.brand_id[>]'] = 0;
            }
            if ($request['wiki_basic_type'] == mWikiBasic::WIKI_BASIC_STORE) {
                $condition['wiki_basic.store_id[>]'] = 0;
            }
        }
        if (isset($request['basic_state']) && strlen($request['basic_state']) > 0 && in_array($request['basic_state'],
                array_keys(self::STATE_MAP))) {
            switch ($request['basic_state']) {
                case 0:
                    $condition['wiki_basic.basic_state'] = [mWikiBasic::STATE_NORMAL, mWikiBasic::STATE_EDIT_AUDIT];
                    $condition['ORDER'] = ['wiki_basic.basic_state' => 'DESC', 'wiki_basic.id' => 'DESC'];
                    break;
                case 1:
                    $condition['wiki_basic.basic_state'] = [mWikiBasic::STATE_ONLINE, mWikiBasic::STATE_PASS];
                    break;
                case 2:
                    $condition['wiki_basic.basic_state'] = [mWikiBasic::STATE_NOT_PASS];
                    break;
            }
        }
        if (isset($request['brand_id']) && !empty($request['brand_id'])) {
            $condition['wiki_basic.brand_id'] = $request['brand_id'];
        } else {
            if (isset($request['brand_uid']) && !empty($request['brand_uid'])) {
                $brandId = mBrand::getBrandIdByUid($request['brand_uid']);
                $condition['wiki_basic.brand_id'] = $brandId;
            } else {
                if (isset($request['brand_name']) && strlen(trim($request['brand_name'])) > 0) {
                    $brandIds = mBrand::getBrandByFilter(['brand_name' => $request['brand_name']], 'id');
                    if ($brandIds) {
                        $condition['wiki_basic.brand_id'] = $brandIds;
                    } else {
                        $condition = null;
                    }
                }
            }
        }

        if (isset($request['store_id']) && !empty($request['store_id'])) {
            $condition['wiki_basic.store_id'] = $request['store_id'];
        } else {
            if (isset($request['store_uid']) && !empty($request['store_uid'])) {
                $storeId = StoreBasic::getStoreInfoByUid($request['store_uid']);
                $condition['wiki_basic.store_id'] = $storeId;
            } else {
                if (isset($request['store_name']) && strlen(trim($request['store_name'])) > 0) {
                    $storeIdArr = StoreBasic::getStoreByFilter(['name' => $request['store_name']], 'id');
                    if ($storeIdArr) {
                        $condition['wiki_basic.store_id'] = $storeIdArr;
                    } else {
                        $condition = null;
                    }
                }
            }
        }

        return $condition;
    }

    private function _getWikiExpand($spuList, $wikiBasicType = 0)
    {
        $row = new Row();
        if ($spuList) {
            $GirdModel = new pGridDataModel($spuList, null, ['pageName' => '']);
            $grid = new Grid($GirdModel);
            $grid->disablePagination();
            $grid->disableCreateButton();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disableTools();
            $grid->disableExport();
            $grid->column('id', '商品id')->width(80);
            $grid->column('title', '标题')->width(400);
            $grid->column('cover_img', '首图')->width(100)->display(function () {
                $imgPath = $this->cover_img;
                $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:200px' class='img img-thumbnail' />" : "";

                return $image;
            });
            $grid->column('channel', '电商平台')->display(function () {
                return '<p>' . $this->channel . '&nbsp;&nbsp;' . $this->channel_spu_id . '</p>' . '<a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'1000px\', \'650px\'],
                                content: \'' . $this->url . '\'
                            });">预览</a>';
            });
            $grid->column('status', '状态')->replace(mWiki::ADM_STATUS_MAP);
            $grid->column('channel_spu_status', '第三方状态')->using(
                mWiki::CHANNEL_STATUS_ARR
                , '未知')->label([
                mWiki::CHANNEL_SPU_STATUS_ON => 'success',
                mWiki::CHANNEL_SPU_STATUS_OFF => 'danger',
            ]);
            $grid->column('is_default', '默认商品')->display(function () {
                return $this->is_default ? '默认' : '否';
            });
            $grid->actions(function (Grid\Displayers\Actions $actions) use ($wikiBasicType) {
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->prepend('&nbsp;<a class="fa" target="_blank" href="' . url('/admin/wiki/admList/' . $actions->row->id . '/edit') . '">编辑</a>');
                if ($wikiBasicType == mWikiBasic::WIKI_BASIC_BRAND) {
                    $actions->prepend('&nbsp;<a class="fa" target="_blank" href="' . url('/admin/wiki/admList?wiki_id=' . $actions->row->id . '&tab_type=2') . '">商品相关操作</a>');
                }
                if ($wikiBasicType == mWikiBasic::WIKI_BASIC_STORE) {
                    $actions->prepend('&nbsp;<a class="fa" target="_blank" href="' . url('/admin/wiki/admList?wiki_id=' . $actions->row->id . '&tab_type=3') . '">商品相关操作</a>');
                }
                if ($actions->row->channel != mWiki::CHANNEL_MAP[mWiki::CHANNEL_NOTHING]) {
                    $actions->prepend('<a class="fa fa-refresh reload-data" data-id="' . $actions->row->id . '"  href="javascript:void(0);")>重新抓取</a>');
                }
            });
            $grid->disablePagination();
            $row->column('12', $grid);

            return $row->render();
        }

        return '';
    }

    public function editAuditList(Request $request, Content $content)
    {
        Admin::style('.span-label{margin-bottom: 5px; cursor: pointer; margin-right: 5px; display: inline-block;}');
        Admin::script($this->editAuditScript());
        Admin::script($this->changeScript());
        Admin::script($this->reloadScript());
        if (!$request->input('basic_state')) {
            $request->merge([
                'basic_state' => 0,
            ]);
        }
        if (!$request->input('wiki_basic_type')) {
            $request->merge([
                'wiki_basic_type' => mWikiBasic::WIKI_BASIC_BRAND,
            ]);
        }
        $request_data = $request->all();
        $condition = self::getAuditEditCondition($request_data);
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $wikiBasicType = $request->input("wiki_basic_type", mWikiBasic::WIKI_BASIC_BRAND);
//        $page = $request->input("page", 1);
        if (!is_null($condition)) {
            $where = $condition;
//            $where['LIMIT'] = [
//                ($page - 1) * $page_size,
//                $page_size,
//            ];
            $result = sAdmWikiBasic::admGetEditAuditWikiList($where);
        } else {
            $result = ['list' => [], 'total' => 0];
        }
        $list = [];
        if ($result['total'] > 0) {
            foreach ($result['list'] as $row) {
                $spuList = $row['spu_list'];
                if ($wikiBasicType == mWikiBasic::WIKI_BASIC_BRAND && $row['brand_id'] > 0 && $row['store_id'] == 0) {
                    $row['expand'] = $this->_getWikiExpand($spuList, $wikiBasicType);
                    $list[] = $row;
                }
                if ($wikiBasicType == mWikiBasic::WIKI_BASIC_STORE && $row['store_id'] > 0 && $row['brand_id'] == 0) {
                    $row['expand'] = $this->_getWikiExpand($spuList, $wikiBasicType);
                    $list[] = $row;
                }
            }
        }
        $gridModel = new pGridDataModel($list, count($list), [
            'perPage' => $page_size,
        ]);
        if ($wikiBasicType == mWikiBasic::WIKI_BASIC_BRAND) {
            $gridList = Admin::grid(
                $gridModel,
                function (Grid $grid) use ($gridModel) {
                    $grid->paginate($gridModel->getPerPage());
                    $grid->disableExport();
                    //$grid->disableRowSelector();
                    $grid->disableCreateButton();
                    $grid->tools(function (Grid\Tools $tools) {
                        $tools->batch(function (BatchActions $batch) {
                            $batch->disableDelete();
                            $batch->add('批量审核通过', new BatchClaimWikiEditAudit(1));
                        });
                    });
                    $grid->filter(function (Grid\Filter $filter) {
                        $filter->disableIdFilter();
                        $filter->column(1 / 2, function ($filter) {
                            $filter->equal('wiki_basic_type', '门店/品牌')->select(mWikiBasic::WIKI_BASIC_TYPE);
                            $filter->equal('wiki_id', 'wiki ID');
                        });
                        $filter->column(1 / 2, function ($filter) {
                            $filter->dropDown('brand_value', [
                                'brand_id' => '品牌ID',
                            ]);
                            $filter->dropDown('store_value', [
                                'store_id' => '门店ID',
                            ]);
                        });

                        $filter->expand();
                    });
                    $grid->column("id", 'wiki ID')->expand(function () {
                        return $this->expand;
                    }, true)->width(80);
                    $grid->column('title', 'wiki 名称')->width(150);
                    $grid->column('cover_img', '图片')->display(function () {
                        $imgPath = $this->cover_img;
                        $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:200px' class='img img-thumbnail' />" : "";

                        return $image;
                    })->width(100);
                    $grid->column('series', '系列')->display(function () {
                        $html = '';
                        $arr = explode(',', $this->series);
                        foreach ($arr as $row) {
                            $html .= '<div class="span-label"><span class="label label-success">' . $row . '</span></div>';
                        }

                        return $html;
                    })->width(150);
                    $grid->column('style', '标签')->display(function () {
                        $html = '';
                        if ($this->style) {
                            $html = '<div>风格</div>';
                            $styleArr = explode(',', $this->style);
                            foreach ($styleArr as $row) {
                                $html .= '<div class="span-label"><span class="label label-success">' . $row . '</span></div>';
                            }
                        }
                        if ($this->material) {
                            $html .= '<div>材质</div>';
                            $materialArr = explode(',', $this->material);
                            foreach ($materialArr as $row) {
                                $html .= '<div class="span-label"><span class="label label-success">' . $row . '</span></div>';
                            }
                        }
                        if ($this->space) {
                            $html .= '<div>所属空间</div>';
                            $spaceArr = explode(',', $this->space);
                            foreach ($spaceArr as $row) {
                                $html .= '<div class="span-label"><span class="label label-success">' . $row . '</span></div>';
                            }
                        }
                        $html .= '</br><a href="javascript:;" class="btn btn-default changeTag" data-type="edit-audit"  data-id="' . $this->id . '" >更改标签</a>';

                        return $html;
                    })->width(200);
                    $grid->column("category_name", '分类')->display(function () {
                        $categoryName = '';
                        if ($this->category_name) {
                            $categoryName .= '<div class="span-label"><span class="label label-success">' . $this->category_name . '</span></div>';
                        }
                        if ($this->second_category_name) {
                            $categoryName .= '<div class="span-label"><span class="label label-success">' . $this->second_category_name . '</span></div>';
                        }
                        if ($this->third_category_name) {
                            $categoryName .= '<div class="span-label"><span class="label label-success">' . $this->third_category_name . '</span></div>';
                        }
                        if ($this->four_category_name) {
                            $categoryName .= '<div class="span-label"><span class="label label-success">' . $this->four_category_name . '</span></div>';
                        }

                        return $categoryName . '</br><a href="javascript:;" class="btn btn-default changeCategory" data-type="edit-audit"   data-id="' . $this->id . '" >更改分类</a>';
                    })->width(100);
                    $grid->column("brand_id", '品牌')->display(function () {
                        $html = '<ul class="list-unstyled">';
                        $html .= "<li><span class='label label-info'>" . '品牌id' . ':' . $this->brand_id . "</span></li>";
                        $html .= "<li><span class='label label-success'>" . '品牌名称' . ':' . $this->brand_name . "</span></li>";
                        $html .= "<li><span class='label label-warning'>" . '品牌类型' . ':' . mBrand::BRAND_TYPE[$this->brand_type] . "</span></li>";
                        $html .= '</ul>';

                        return $html;
                    })->width(150);
                    $grid->column("brand_logo", '品牌logo')->display(function () {
                        $imgPath = $this->brand_logo;
                        $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:200px' class='img img-thumbnail' />" : "";

                        return $image;
                    })->width(80);
                    $grid->column("basic_state_desc", '状态')->width(80);
                    $grid->actions(function (Grid\Displayers\Actions $actions) {
                        $actions->disableEdit();
                        $actions->disableDelete();
                        $actions->prepend('&nbsp;<a class="fa edit-pass-data" data-state="' . mWikiBasic::STATE_PASS . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">审核通过</a>');
                        $actions->prepend('&nbsp;<a class="fa edit-not-pass-data" data-state="' . mWikiBasic::STATE_NOT_PASS . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">审核不通过</a>');
                    });
                }
            );
        } else {
            $gridList = Admin::grid(
                $gridModel,
                function (Grid $grid) use ($gridModel) {
                    $grid->paginate($gridModel->getPerPage());
                    $grid->disableExport();
                    //$grid->disableRowSelector();
                    $grid->disableCreateButton();
                    $grid->tools(function (Grid\Tools $tools) {
                        $tools->batch(function (BatchActions $batch) {
                            $batch->disableDelete();
                            $batch->add('批量审核通过', new BatchClaimWikiEditAudit(1));
                        });
                    });
                    $grid->filter(function (Grid\Filter $filter) {
                        $filter->disableIdFilter();
                        $filter->column(1 / 2, function ($filter) {
                            $filter->equal('wiki_basic_type', '门店/品牌')->select(mWikiBasic::WIKI_BASIC_TYPE);
                            $filter->equal('wiki_id', 'wiki ID');
                        });
                        $filter->column(1 / 2, function ($filter) {
                            $filter->dropDown('brand_value', [
                                'brand_id' => '品牌ID',
                            ]);
                            $filter->dropDown('store_value', [
                                'store_id' => '门店ID',
                            ]);
                        });

                        $filter->expand();
                    });
                    $grid->column("id", 'wiki ID')->expand(function () {
                        return $this->expand;
                    }, true)->width(80);
                    $grid->column('title', 'wiki 名称')->width(150);
                    $grid->column('cover_img', '图片')->display(function () {
                        $imgPath = $this->cover_img;
                        $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:200px' class='img img-thumbnail' />" : "";

                        return $image;
                    })->width(100);
                    $grid->column('series', '系列')->display(function () {
                        $html = '';
                        $arr = explode(',', $this->series);
                        foreach ($arr as $row) {
                            $html .= '<div class="span-label"><span class="label label-success">' . $row . '</span></div>';
                        }

                        return $html;
                    })->width(150);
                    $grid->column('style', '标签')->display(function () {
                        $html = '';
                        if ($this->style) {
                            $html = '<div>风格</div>';
                            $styleArr = explode(',', $this->style);
                            foreach ($styleArr as $row) {
                                $html .= '<div class="span-label"><span class="label label-success">' . $row . '</span></div>';
                            }
                        }
                        if ($this->material) {
                            $html .= '<div>材质</div>';
                            $materialArr = explode(',', $this->material);
                            foreach ($materialArr as $row) {
                                $html .= '<div class="span-label"><span class="label label-success">' . $row . '</span></div>';
                            }
                        }
                        if ($this->space) {
                            $html .= '<div>所属空间</div>';
                            $spaceArr = explode(',', $this->space);
                            foreach ($spaceArr as $row) {
                                $html .= '<div class="span-label"><span class="label label-success">' . $row . '</span></div>';
                            }
                        }
                        $html .= '</br><a href="javascript:;" class="btn btn-default changeTag" data-type="edit-audit"  data-id="' . $this->id . '" >更改标签</a>';

                        return $html;
                    })->width(200);
                    $grid->column("category_name", '分类')->display(function () {
                        $categoryName = '';
                        if ($this->category_name) {
                            $categoryName .= '<div class="span-label"><span class="label label-success">' . $this->category_name . '</span></div>';
                        }
                        if ($this->second_category_name) {
                            $categoryName .= '<div class="span-label"><span class="label label-success">' . $this->second_category_name . '</span></div>';
                        }
                        if ($this->third_category_name) {
                            $categoryName .= '<div class="span-label"><span class="label label-success">' . $this->third_category_name . '</span></div>';
                        }
                        if ($this->four_category_name) {
                            $categoryName .= '<div class="span-label"><span class="label label-success">' . $this->four_category_name . '</span></div>';
                        }

                        return $categoryName . '</br><a href="javascript:;" class="btn btn-default changeCategory" data-type="edit-audit"   data-id="' . $this->id . '" >更改分类</a>';
                    })->width(100);
                    $grid->column("store_id", '门店')->display(function () {
                        $html = '<ul class="list-unstyled">';
                        $html .= "<li><span class='label label-info'>" . '门店id' . ':' . $this->store_id . "</span></li>";
                        $html .= "<li><span class='label label-success'>" . '门店名称' . ':' . $this->store_name . "</span></li>";
                        $html .= '</ul>';

                        return $html;
                    })->width(150);
                    $grid->column("store_logo", '门店logo')->display(function () {
                        $imgPath = $this->store_logo;
                        $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:200px' class='img img-thumbnail' />" : "";

                        return $image;
                    })->width(80);
                    $grid->column("basic_state_desc", '状态')->width(80);
                    $grid->actions(function (Grid\Displayers\Actions $actions) {
                        $actions->disableEdit();
                        $actions->disableDelete();
                        $actions->prepend('&nbsp;<a class="fa edit-pass-data" data-state="' . mWikiBasic::STATE_PASS . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">审核通过</a>');
                        $actions->prepend('&nbsp;<a class="fa edit-not-pass-data" data-state="' . mWikiBasic::STATE_NOT_PASS . '" data-id="' . $actions->row->id . '" href="javascript:void(0);">审核不通过</a>');
                    });
                }
            );
        }

        $tab = new Tab();
        $tab->addLink('品牌/门店wiki审核', url('/admin/brand/wiki/list'), false);
        $tab->add('品牌/门店wiki编辑待审核', $gridList->render(), true);
        $tab->addLink('品牌/门店wiki图片审核', url('/admin/brand/wiki/imagelist'), false);
        $content->row($tab);

        return $content
            ->header('品牌/门店wiki编辑待审核')
            ->description(' ')
            ->breadcrumb(['text' => '品牌/门店wiki编辑待审核']);
    }

    private function editAuditScript()
    {
        return <<<SCRIPT
        $('.edit-pass-data').unbind('click').click(function(){
            var id= $(this).data('id');
            var state=$(this).data('state');
            let url = '/admin/brand/wiki/editAuditList/audit'
            let params = {id:id,state:state}
            $.post(url, params , function (result) {
                if (result.code == 1) {
                    layer.msg(result.title);
                    setTimeout(function () {
                        parent.window.location.reload();
                    }, 2000);
                } else {
                    layer.msg(result.title);
                }
            });
        });
        $('.edit-not-pass-data').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.open({
                type: 2,
                title: '审核不通过',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['700px', '600px'],
                content: '/admin/brand/wiki/editAuditList/'+id+'/editUnPass',
//                end: function(){
//                    parent.window.location.reload();
//                }
            });
        });
SCRIPT;
    }

    private static function getAuditEditCondition($request)
    {
        $condition = [];
        if (isset($request['wiki_id']) && !empty($request['wiki_id'])) {
            $condition['basic_id'] = $request['wiki_id'];

            return $condition;
        }
        if (isset($request['brand_id']) && !empty($request['brand_id'])) {
            $basicIds = mWikiBasic::selectByWhere(['brand_id' => $request['brand_id']], 'id');
            if ($basicIds) {
                $condition['basic_id'] = $basicIds;
            } else {
                $condition = null;
            }
        }
        if (isset($request['store_id']) && !empty($request['store_id'])) {
            $basicIds = mWikiBasic::selectByWhere(['store_id' => $request['store_id']], 'id');
            if ($basicIds) {
                $condition['basic_id'] = $basicIds;
            } else {
                $condition = null;
            }
        }

        return $condition;
    }

    public function audit(Request $request)
    {
        try {
            $adminId = Admin::user()->id;
            $id = $request->input('id', 0);
            $state = $request->input('state', null);
            $reason = $request->input('reason', '');
            if ($id && !is_null($state)) {
                AdmWikiBasic::audit($id, $state, $adminId, $reason);
                $success = [
                    'title' => '操作成功',
                    'code' => 1,
                ];
            }
        } catch (Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }

        return response()->json($success);
    }

    /**
     * 审核通过-多条
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function audits(Request $request)
    {
        try {
            $params = $request->all();
            $adminId = Admin::user()->id;
            $ids = $params['ids'];
            if ($ids) {
                AdmWikiBasic::audits($ids, $adminId);
                $success = [
                    'title' => '操作成功',
                    'code' => 1,
                ];
            }
        } catch (Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }

        return response()->json($success);

    }

    public function editAudit(Request $request)
    {
        try {
            $adminId = Admin::user()->id;
            $id = $request->input('id', 0);
            $state = $request->input('state', null);
            $reason = $request->input('reason', '');
            if ($id && !is_null($state)) {
                AdmWikiBasic::editAuditWiki($id, $state, $adminId, $reason);
                $success = [
                    'title' => '操作成功',
                    'code' => 1,
                ];
            }
        } catch (Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }

        return response()->json($success);
    }

    /**
     * 批量审核通过编辑待审核的数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function editAudits(Request $request)
    {
        try {
            $params = $request->all();
            $adminId = Admin::user()->id;
            $ids = $params['ids'];
            foreach ($ids as $id) {
                AdmWikiBasic::editAuditWiki($id, mWikiBasic::STATE_PASS, $adminId, '');
            }
            $success = [
                'title' => '操作成功',
                'code' => 1
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '操作失败,' . $e->getMessage(),
                'msg' => '信息：' . $e->getFile() . $e->getLine(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }


    public function unPass(Request $request, WorkContent $content, $id)
    {
        Admin::script(self::unPassScript());
        $form = new Form(['id' => $id, 'state' => mWikiBasic::STATE_NOT_PASS]);
        $form->attribute('class', 'unpass');
        $form->hidden('id', 'id');
        $form->hidden('state', 'state');
        $form->textarea('reason', '原因');
        $form->html('<div class="col-md-8"><div class="btn-group pull-right"><button type="button" class="btn btn-info pull-right btn-unpass">确定</button></div></div>');
        $form->disableSubmit();
        $form->disableReset();

        return $content
            ->body($form);
    }

    private function unPassScript()
    {
        return <<<SCRIPT
        $('.btn-unpass').unbind('click').click(function(){
            var id= $('input[name="id"]').val();
            console.log(id);
            var reason=$('textarea[name="reason"]').val();
            console.log(reason);
            var state=$('input[name="state"]').val();
            console.log(state);
            let url = '/admin/brand/wiki/audit'
            let params = {id:id,state:state,reason:reason}
            $.post(url, params , function (result) {
                if (result.code == 1) {
                    layer.msg(result.title);
                    setTimeout(function () {
                        parent.window.location.reload();
                    }, 2000);
                } else {
                    layer.msg(result.title);
                }
            });
        });
SCRIPT;
    }

    public function editUnPass(Request $request, WorkContent $content, $id)
    {
        Admin::script(self::eidtUnPassScript());
        $form = new Form(['id' => $id, 'state' => mWikiBasic::STATE_NOT_PASS]);
        $form->attribute('class', 'unpass');
        $form->hidden('id', 'id');
        $form->hidden('state', 'state');
        $form->textarea('reason', '原因');
        $form->html('<div class="col-md-8"><div class="btn-group pull-right"><button type="button" class="btn btn-info pull-right btn-editunpass">确定</button></div></div>');
        $form->disableSubmit();
        $form->disableReset();

        return $content
            ->body($form);
    }

    private function eidtUnPassScript()
    {
        return <<<SCRIPT
        $('.btn-editunpass').unbind('click').click(function(){
            var id= $('input[name="id"]').val();
            console.log(id);
            var reason=$('textarea[name="reason"]').val();
            console.log(reason);
            var state=$('input[name="state"]').val();
            console.log(state);
            let url = '/admin/brand/wiki/editAuditList/audit'
            let params = {id:id,state:state,reason:reason}
            $.post(url, params , function (result) {
                if (result.code == 1) {
                    layer.msg(result.title);
                    setTimeout(function () {
                        parent.window.location.reload();
                    }, 2000);
                } else {
                    layer.msg(result.title);
                }
            });
        });
SCRIPT;
    }

    public function changeCategory(Request $request, WorkContent $content, $id)
    {
        $type = $request->input('type', '');
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
SCRIPT;
            Admin::script($script);
        }

        if ($type != 'edit-audit') {
            $info = mWikiBasic::getByWhere(['id' => $id]);
        } else {
            $info = mWikiBasicLog::getByWhere([
                'basic_id' => $id,
                'operate_type' => mWikiBasicLog::OPERATE_TYPE_BRAND_EDIT_AUDIT,
                'operate_value' => mWikiBasicLog::OPERATE_BRAND_EDIT_AUDIT_VALUE,
                'log_state' => mWikiBasicLog::STATE_NORMAL,
            ]);
            $info = $info ? json_decode($info['operate_data'], true) : [];
            $info = $info ? $info['basic'] : [];
        }
        //区分门店和品牌的wiki分类数据展示
        $flag = 1;
        if ($info['store_id'] > 0 && $info['brand_id'] == 0) {
            $flag = 2;
        }
        $options = Category::admAllCate4Select($flag);
        $info['data-type'] = $type;
        $full_category = [];
        if ($info['category_id']) {
            $full_category[] = $info['category_id'];
        }
        if ($info['second_category_id']) {
            $full_category[] = $info['second_category_id'];
        }
        if ($info['third_category_id']) {
            $full_category[] = $info['third_category_id'];
        }
        if ($info['four_category_id']) {
            $full_category[] = $info['four_category_id'];
        }
        $info['full_category'] = implode('_', $full_category);
        $form = new Form($info);
//        $topCategory = sAdmWikiBasic::admGetChildCategoryMap(0);
//        $secondCategory = isset($info['category_id']) && $info['category_id'] ? sAdmWikiBasic::admGetChildCategoryMap($info['category_id']) : [];
//        $thirdCategory = isset($info['second_category_id']) && $info['second_category_id'] ? sAdmWikiBasic::admGetChildCategoryMap($info['second_category_id']) : [];
//        $fourthCategory = isset($info['third_category_id']) && $info['third_category_id'] ? sAdmWikiBasic::admGetChildCategoryMap($info['third_category_id']) : [];
//        $form->select('category_id', '一级类目')->options($topCategory)->load('second_category_id', self::SOURCE_CATEGORY_LIST);
//        $form->select('second_category_id', '二级类目')->options($secondCategory)->load('third_category_id', self::SOURCE_CATEGORY_LIST);
//        $form->select('third_category_id', '三级类目')->options($thirdCategory)->load('four_category_id', self::SOURCE_CATEGORY_LIST);
//        $form->select('four_category_id', '四级类目')->options($fourthCategory);
        $form->select('full_category', '类目列表')->options($options);
        $form->hidden('data-type', 'data-type');
        $form->action('/admin/brand/wiki/changeCategory/' . $id . '/save');

        return $content
            ->body($form);
    }

    public function postChangeCategory(Request $request, $id)
    {
        $request = $request->all();
        $full_category = $request['full_category'] ?? '';
        $full_category = explode('_', $full_category);
        $categoryId = $full_category[0] ?? 0;
        $secondCategoryId = $full_category[1] ?? 0;
        $thirdCategoryId = $full_category[2] ?? 0;
        $fourCategoryId = $full_category[3] ?? 0;
        $dataType = $request['data-type'];
        if ($dataType != 'edit-audit') {
            $info = mWikiBasic::getByWhere(['id' => $id]);
            if ($info && $categoryId && $secondCategoryId) {
                $lastCategoryId = $fourCategoryId ? $fourCategoryId : ($thirdCategoryId ? $thirdCategoryId : ($secondCategoryId ? $secondCategoryId : $categoryId));
                $data = [
                    'category_id' => $categoryId,
                    'second_category_id' => $secondCategoryId,
                    'third_category_id' => $thirdCategoryId,
                    'four_category_id' => $fourCategoryId,
                    'last_category_id' => $lastCategoryId,
                ];
                mWikiBasic::updateData($data, ['id' => $id]);
                mWiki::updateData($data, ['basic_id' => $id]);
                $success = new MessageBag([
                    'title' => '修改成功',
                ]);

                return redirect('/admin/brand/wiki/changeCategory/' . $id . '?code=1&type=' . $dataType)->with(compact('success'));
            }
        } else {
            $info = mWikiBasicLog::getByWhere([
                'basic_id' => $id,
                'operate_type' => mWikiBasicLog::OPERATE_TYPE_BRAND_EDIT_AUDIT,
                'operate_value' => mWikiBasicLog::OPERATE_BRAND_EDIT_AUDIT_VALUE,
                'log_state' => mWikiBasicLog::STATE_NORMAL,
            ]);
            $operateData = $info ? json_decode($info['operate_data'], true) : [];
            if ($info && $categoryId && $secondCategoryId) {
                $lastCategoryId = $fourCategoryId ? $fourCategoryId : ($thirdCategoryId ? $thirdCategoryId : ($secondCategoryId ? $secondCategoryId : $categoryId));
                $operateData['basic']['category_id'] = $categoryId;
                $operateData['basic']['second_category_id'] = $secondCategoryId;
                $operateData['basic']['third_category_id'] = $thirdCategoryId;
                $operateData['basic']['four_category_id'] = $fourCategoryId;
                $operateData['basic']['last_category_id'] = $lastCategoryId;
                mWikiBasicLog::updateData(['operate_data' => json_encode($operateData, JSON_UNESCAPED_UNICODE)],
                    ['id' => $info['id']]);
                $success = new MessageBag([
                    'title' => '修改成功',
                ]);

                return redirect('/admin/brand/wiki/changeCategory/' . $id . '?code=1&type=' . $dataType)->with(compact('success'));
            }
        }
        $error = new MessageBag([
            'title' => '修改失败',
        ]);

        return back()->with(compact('error'));
    }

    public function changeTag(Request $request, WorkContent $content, $id)
    {
        $type = $request->input('type', '');
        $code = $request->input('code', 0);
        if ($code == 1) {
            $script = <<<SCRIPT
            setTimeout(function () {
                        parent.window.location.reload();
                    }, 1000);
SCRIPT;
            Admin::script($script);
        }
        if ($type != 'edit-audit') {
            $info = mWikiBasic::getByWhere(['id' => $id]);
        } else {
            $info = mWikiBasicLog::getByWhere([
                'basic_id' => $id,
                'operate_type' => mWikiBasicLog::OPERATE_TYPE_BRAND_EDIT_AUDIT,
                'operate_value' => mWikiBasicLog::OPERATE_BRAND_EDIT_AUDIT_VALUE,
                'log_state' => mWikiBasicLog::STATE_NORMAL,
            ]);
            $info = $info ? json_decode($info['operate_data'], true) : [];
            $info = $info ? $info['basic'] : [];
        }
        $info['data-type'] = $type;
        $info['style'] = explode(',', $info['style']);
        $info['material'] = explode(',', $info['material']);
        $info['space'] = explode(',', $info['space']);
        $tags = Tag::getAttrTagsWiki();
        $tagList = [];
        foreach ($tags as $row) {
            if ($row['parent_id'] == 399) {//空间
                $tagList['space_list'][] = $row['tag'];
            } else {
                if ($row['parent_id'] == 119) {//风格
                    $tagList['style_list'][] = $row['tag'];
                } else {
                    if ($row['parent_id'] == 139) {//材质
                        $tagList['material_list'][] = $row['tag'];
                    }
                }
            }
        }

        $form = new Form($info);
        $form->tags('style', '风格')->options($tagList['style_list']);
        $form->tags('material', '材质')->options($tagList['material_list']);
        $form->tags('space', '所属空间')->options($tagList['space_list']);
        $form->hidden('data-type', 'data-type');
        $form->action('/admin/brand/wiki/changeTag/' . $id . '/save');

        return $content
            ->body($form);
    }

    public function postChangeTag(Request $request, $id)
    {
        $request = $request->all();
        $style = $request['style'];
        $material = $request['material'];
        $space = $request['space'];
        $dataType = $request['data-type'];
        $style = array_filter($style);
        $material = array_filter($material);
        $space = array_filter($space);
        if ($dataType != 'edit-audit') {
            $info = mWikiBasic::getByWhere(['id' => $id]);
            if ($info) {
                $data = [
                    'style' => $style ? implode(',', $style) : '',
                    'material' => $material ? implode(',', $material) : '',
                    'space' => $space ? implode(',', $space) : '',
                ];
                mWikiBasic::updateData($data, ['id' => $id]);
                $success = new MessageBag([
                    'title' => '修改成功',
                ]);

                return redirect('/admin/brand/wiki/changeTag/' . $id . '?code=1&type=' . $dataType)->with(compact('success'));
            }
        } else {
            $info = mWikiBasicLog::getByWhere([
                'basic_id' => $id,
                'operate_type' => mWikiBasicLog::OPERATE_TYPE_BRAND_EDIT_AUDIT,
                'operate_value' => mWikiBasicLog::OPERATE_BRAND_EDIT_AUDIT_VALUE,
                'log_state' => mWikiBasicLog::STATE_NORMAL,
            ]);
            $operateData = $info ? json_decode($info['operate_data'], true) : [];
            if ($info) {
                $operateData['basic']['style'] = $style ? implode(',', $style) : '';
                $operateData['basic']['material'] = $material ? implode(',', $material) : '';
                $operateData['basic']['space'] = $space ? implode(',', $space) : '';
                mWikiBasicLog::updateData(['operate_data' => json_encode($operateData, JSON_UNESCAPED_UNICODE)],
                    ['id' => $info['id']]);
                $success = new MessageBag([
                    'title' => '修改成功',
                ]);

                return redirect('/admin/brand/wiki/changeTag/' . $id . '?code=1&type=' . $dataType)->with(compact('success'));
            }
        }
        $error = new MessageBag([
            'title' => '修改失败',
        ]);

        return back()->with(compact('error'));
    }

    /**
     * 品牌 Wiki 支持运营上传商品主图-保存修改
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function wikiImgSave(Request $request)
    {
        try {
            $params = $request->post();
            if (empty($params['id']) || $params['id'] <= 0) {
                throw new UnexpectedValueException('非法提交');
            }
            $info = mWikiBasic::get('id', ['id' => $params['id']]);
            if (!$info) {
                throw new UnexpectedValueException('wiki不存在');
            }
            $imgs = isset($params['imgs']) ? explode(',', $params['imgs']) : [];
            //图片数量
            $count = count($imgs);
            if ($count > 5) {
                throw new Exception('主图不能超过5张');
            }
            $where['id'] = $params['id'];
            $imgs = array_filter($imgs);
            $new_imgs = [];
            foreach ($imgs as $k => $img) {
                $new_imgs[$k]['status'] = WikiBasic::WIKI_BASIC_IMAGE_STATUS_DONE;
                $new_imgs[$k]['img'] = $img;
            }

            //拼装新的更新数据
            $upData = [
                'cover_img' => isset($imgs[0]) ? $imgs[0] : '',
                'imgs' => $new_imgs ? json_encode($new_imgs) : '',
            ];
            $rs = AdmWikiBasic::upInfo($upData, $where);
            if (!$rs) {
                throw new Exception('提交失败');
            }
            $success = new MessageBag([
                'title' => '提交成功',
            ]);
        } catch (UnexpectedValueException $ue) {
            $error = new MessageBag(['title' => $ue->getMessage()]);

            return redirect('/admin/brand/wiki')->with(compact('error'));
        } catch (Exception $e) {
            $error = new MessageBag(['title' => $e->getMessage()]);

            return redirect('/admin/brand/wiki/img/edit?id=' . $params['id'])->with(compact('error'));
        }

        return redirect('/admin/brand/wiki/img/edit?id=' . $params['id'])->with(compact('success'));
    }

    /**
     * 品牌 Wiki 支持运营上传商品主图-展示修改
     * @param Request $request
     * @param Content $content
     * @param int $id
     * @return Content
     */
    public function wikiImgEdit(Request $request, Content $content)
    {
        $params = $request->all();
        $id = isset($params['id']) ? $params['id'] : 0;
        $data = AdmWikiBasic::getImgs($id, ['cover_img', 'id', 'imgs']);
        //参数合法校验
        if ($params['id'] <= 0 || !$data) {
            $error = new MessageBag([
                'title' => '非法提交',
            ]);

            return redirect('/admin/brand/wiki')->with(compact('error'));
        }

        $data['imgs'] = empty($data['imgs']) ? '' : implode(',', $data['imgs']);
        $baseForm = new Form($data);
        $baseForm->disableReset();
        $baseForm->imgUpload('imgs', '商品主图', true, [
            'isUpload' => true,
            'isGetUrl' => true,
            'imgType' => ImgUrl::APPTYPE_BIZ,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_NPHONE,
        ])->help("直接覆盖商家自行修改的图片");
        $baseForm->hidden('id', $data['id']);
        $baseForm->action('/admin/brand/wiki/img/save');

        return $content
            ->header('')
            ->breadcrumb(
                ['text' => 'wiki商品', 'url' => '/brand/wiki'],
                ['text' => '图片修改']
            )
            ->row($baseForm);
    }

    public function unPassLog(Request $request, WorkContent $content, $id)
    {
        $list = mWikiBasicLog::selectByWhere([
            'basic_id' => $id,
            'operate_type' => mWikiBasicLog::OPERATE_TYPE_AUDIT,
            'operate_value' => mWikiBasic::STATE_NOT_PASS,
            'log_state[!]' => mWikiBasicLog::STATE_DEL,
        ]);
        $rows = [];
        foreach ($list as $row) {
            $operateData = json_decode($row['operate_data'], true);
            $reason = $operateData['reason'];
            $rows[] = [
                $reason,
                $row['addtime'],
                Admin::user()->find($row['admin_id'])->name,
            ];
        }
        $table = new Table(['不通过原因', '操作时间', '管理员'], $rows);

        return $content
            ->body($table);
    }

    public function editableWiki(Request $request, $id)
    {
        $name = $request->input('name', '');
        $value = $request->input('value', '');
        try {
            if ($name == 'title' && $value && $id) {
                mWikiBasic::updateData(['title' => $value], ['id' => $id]);
            }
            return response()->json([
                'status' => true,
            ]);
        } catch (\Exception $e) {
            return response()->json(['errors' => [$message = $e->getMessage()]], 422);
        }
    }
}
